package com.mall.alipay.controller;

import com.mall.alipay.common.R;
import com.mall.alipay.common.ResultCodeEnum;
import com.mall.alipay.entity.UserInfo;
import com.mall.alipay.service.UserInfoService;
import com.mall.alipay.util.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserInfoService userInfoService;

    /**
     * 获取用户信息
     * @param username
     * @return
     */
    @GetMapping("/getUserInfo")
    public R getUserInfo(@RequestParam String username){
        JWTUtils jwtUtils = new JWTUtils();
        String s = jwtUtils.generateToken(username);

        Claims claimsByToken = jwtUtils.getClaimsByToken(s);
        System.out.println(claimsByToken);

        boolean tokenExpired = jwtUtils.isTokenExpired(claimsByToken);
        System.out.println(tokenExpired);
        return R.setResult(ResultCodeEnum.SUCCESS).data(userInfoService.getUserInfo(username));
    }

    /**
     * 新增用户
     * @param userInfo
     * @return
     */
//    @PreAuthorize("hasAnyRole('admin')")
    @PostMapping("/addUserInfo")
    public R addUserInfo(@RequestBody UserInfo userInfo){
        int i = userInfoService.addUserInfo(userInfo);
        if (i <= 0) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 查看登录用户信息
     */
    @GetMapping("/getAuth")
    public Authentication getAuth(){
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
